import {createRouter, createWebHistory} from 'vue-router'
import Home from '../views/Home.vue'
import Login from '../views/Login.vue'
import BlogDetail from '../components/BlogDetail.vue'
import Blogs from '../components/Blogs.vue'
import BlogEdit from '../components/BlogEdit.vue'
import error from '../components/404/404.vue'

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: '/',
            name: 'home',
            component: Home,
            redirect: {name: 'Blogs'},
            children: [
                {
                    path: '/blogs',
                    name: 'Blogs',
                    component: Blogs,
                },
                {
                    path: '/blog/:blogId',
                    name: 'BlogDetail',
                    component: BlogDetail
                },
                {
                    path: '/blogEdit/:blogId',
                    name: 'BlogEdit',
                    component: BlogEdit
                }
            ]
        },
        {
            path: '/login',
            name: 'login',
            component: Login
        },
        {
            path: '/404',
            name: 'error',
            component: error
        }
    ]
})

router.beforeEach((to, from, next) => {
    if (to.matched.length === 0) {
        next('/404')
    } else {
        next()
    }
})

export default router
